<template>
  <div>
    <Top/>
    <search @search="changeOriginalData(1)"/>
    <div  id="content">
      <article-list @changepage1="changeOriginalData($event)" v-if="latestArticles.length!==0" :articles="latestArticles" :page-num="pageNum" :total-num="totalNum"/>
      <div class="loading" v-else-if="latestArticles.length===0  && isDataFetched"> 没有找到相关文章，请换个关键词试试！。。。 </div>
      <div class="loading" v-else-if="latestArticles.length ===0 && !isDataFetched"> 正在马不停蹄地赶来！。。。。 </div>
      <article-list-right @searchWithTag="changeOriginalData(1)" :hot-articles="hotArticles"/>
    </div>
    <copyright/>
  </div>
</template>

<script>
import Top from "../base/top";
import ArticleList from "./ArticleList";
import ArticleListRight from "./ArticleListRight";
import Copyright from "../base/copyright";
import Search from "./Search";
import axios from "axios";
import {ip} from "../../data/ip";
export default {
  components:{Top,ArticleList,ArticleListRight,Search,Copyright},
  name: "index",
  data(){
    return {
      latestArticles: null,
      hotArticles: null,
      pageNum : 0,
      totalNum: 0,
      isDataFetched: false
    }
  },
  mounted(){
    window.sessionStorage.setItem("keyword","")
    window.sessionStorage.setItem("tag","")
    this.acquireOriginalData()
  },
  methods:{
    acquireOriginalData(){
      axios({
        url: ip + "/api/index",
        method:"get",
        timeout:1000*10
      }).then(res=>{
        console.log(res.data)
        this.latestArticles = res.data.latestArticles
        this.hotArticles = res.data.hotArticles
        this.pageNum = res.data.pageNum
        this.totalNum = res.data.totalNum
      }).catch(err=>{
        alert("服务器错误！")
      })
    },//acquireOriginalData
    changeOriginalData(x){
      axios({
        url: ip + "/api/change-page",
        method:"get",
        params: {
          pageNum: x,
          keyword: window.sessionStorage.getItem("keyword"),
          tag: window.sessionStorage.getItem("tag")
        }
      }).then(res=>{
        if(!res.data.articles){
          this.latestArticles = []
        }
        else{
          this.latestArticles = res.data.articles
        }
        this.latestArticles.length >0   ? this.isDataFetched = false :this.isDataFetched = true
        this.pageNum = res.data.pageNum
        this.totalNum = res.data.totalNum
      }).catch(err=>{
        alert("服务器错误2")
      })
    },//changeOriginalData

  }
}
</script>

<style lang="less">
*{
  margin:0;
  padding: 0;
}
#content{
  margin:0 auto;
  width:85%;
}
#content > div {
  display: inline-block;
}
#content > div:first-child{
  width:70%;
}
#content > div:last-child{
  width:28%;
  vertical-align: top;
}

.loading{
  text-align: center;
  font-size:30px;
  margin-top:100px;
  color:#ccc;
}
</style>
